<!DOCTYPE html>












  


<html class="theme-next muse use-motion" lang="zh-CN">
<head>
  <meta charset="UTF-8">
<meta http-equiv="X-UA-Compatible" content="IE=edge">
<meta name="viewport" content="width=device-width, initial-scale=1, maximum-scale=2">
<meta name="theme-color" content="#222">






  
  
    
      
    
    
      
    
  <script src="//cdnjs.cloudflare.com/ajax/libs/pace/1.0.2/pace.min.js"></script>
  <link href="//cdnjs.cloudflare.com/ajax/libs/pace/1.0.2/themes/blue/pace-theme-flash.min.css" rel="stylesheet">



<script>
    (function () {
        if ('') {
            if (prompt('请输入文章密码') !== '') {
                alert('密码错误！');
                if (history.length === 1) {
                    location.replace("http://xxxxxxx.xxx"); // 这里替换成你的首页
                } else {
                    history.back();
                }
            }
        }
    })();
</script>





<meta http-equiv="Cache-Control" content="no-transform">
<meta http-equiv="Cache-Control" content="no-siteapp">



  <meta name="google-site-verification" content="zrNUWIf25v2J4dC1wliso_DUXEwYoECv4j3h9CE34xM">








  <meta name="baidu-site-verification" content="nuHze5uXZ7">







  
  
    
  
  <link href="//cdn.jsdelivr.net/fancybox/2.1.5/jquery.fancybox.min.css" rel="stylesheet" type="text/css">




  
  
  
  

  
    
    
  

  
    
      
    

    
  

  

  

  
    
      
    

    
  

  
    
    
    <link href="https://fonts.cat.net/css?family=Lato:300,300italic,400,400italic,700,700italic|Roboto Slab:300,300italic,400,400italic,700,700italic|Roboto Mono:300,300italic,400,400italic,700,700italic&subset=latin,latin-ext" rel="stylesheet" type="text/css">
  






  

<link href="//cdnjs.cloudflare.com/ajax/libs/font-awesome/4.7.0/css/font-awesome.min.css" rel="stylesheet" type="text/css">




<link href="/css/main.css?v=6.4.2" rel="stylesheet" type="text/css">


  <link rel="apple-touch-icon" sizes="180x180" href="/images/apple-touch-icon-next.png?v=6.4.2">


  <link rel="icon" type="image/png" sizes="32x32" href="/images/favicon-32x32-next.ico?v=6.4.2">


  <link rel="icon" type="image/png" sizes="16x16" href="/images/favicon-16x16-next.png?v=6.4.2">


  <link rel="mask-icon" href="/images/logo.svg?v=6.4.2" color="#222">









<script type="text/javascript" id="hexo.configurations">
  var NexT = window.NexT || {};
  var CONFIG = {
    root: '/',
    scheme: 'Muse',
    version: '6.4.2',
    sidebar: {"position":"left","display":"always","offset":12,"b2t":false,"scrollpercent":true,"onmobile":false},
    fancybox: true,
    fastclick: false,
    lazyload: false,
    tabs: true,
    motion: {"enable":true,"async":false,"transition":{"post_block":"fadeIn","post_header":"slideDownIn","post_body":"slideDownIn","coll_header":"slideLeftIn","sidebar":"slideUpIn"}},
    algolia: {
      applicationID: '',
      apiKey: '',
      indexName: '',
      hits: {"per_page":10},
      labels: {"input_placeholder":"Search for Posts","hits_empty":"We didn't find any results for the search: ${query}","hits_stats":"${hits} results found in ${time} ms"}
    }
  };
</script>


  




  <meta name="keywords" content="docker,服务器">
<meta property="og:type" content="article">
<meta property="og:title" content="本博客服务器docker配置">
<meta property="og:url" content="https://blog.codenote.pro/this-blog-server-docker-configuration.html">
<meta property="og:site_name" content="九阳的笔记本">
<meta property="og:locale" content="zh-CN">
<meta property="og:image" content="https://blog.codenote.pro/this-blog-server-docker-configuration.html">
<meta property="og:updated_time" content="2018-11-01T16:22:00.487Z">
<meta name="twitter:card" content="summary">
<meta name="twitter:title" content="本博客服务器docker配置">
<meta name="twitter:image" content="https://blog.codenote.pro/this-blog-server-docker-configuration.html">



  <link rel="alternate" href="/atom.xml" title="九阳的笔记本" type="application/atom+xml">




  <link rel="canonical" href="https://blog.codenote.pro/this-blog-server-docker-configuration.html">



<script type="text/javascript" id="page.configurations">
  CONFIG.page = {
    sidebar: "",
  };
</script>

  <title>本博客服务器docker配置 | 九阳的笔记本</title>
  




<script async src="https://www.googletagmanager.com/gtag/js?id=UA-126970002-1"></script>
<script>
  window.dataLayer = window.dataLayer || [];
  function gtag(){dataLayer.push(arguments);}
  gtag('js', new Date());

  gtag('config', 'UA-126970002-1');
</script>



  <script type="text/javascript">
    var _hmt = _hmt || [];
    (function() {
      var hm = document.createElement("script");
      hm.src = "https://hm.baidu.com/hm.js?07b2f6778635ec267ee2b4753e118da9";
      var s = document.getElementsByTagName("script")[0];
      s.parentNode.insertBefore(hm, s);
    })();
  </script>




  <noscript>
  <style type="text/css">
    .use-motion .motion-element,
    .use-motion .brand,
    .use-motion .menu-item,
    .sidebar-inner,
    .use-motion .post-block,
    .use-motion .pagination,
    .use-motion .comments,
    .use-motion .post-header,
    .use-motion .post-body,
    .use-motion .collection-title { opacity: initial; }

    .use-motion .logo,
    .use-motion .site-title,
    .use-motion .site-subtitle {
      opacity: initial;
      top: initial;
    }

    .use-motion {
      .logo-line-before i { left: initial; }
      .logo-line-after i { right: initial; }
    }
  </style>
</noscript>

</head>

<body itemscope="" itemtype="http://schema.org/WebPage" lang="zh-CN">

  
  
    
  

  <div class="container sidebar-position-left page-post-detail">
    <div class="headband"></div>
     
    
    
    <header id="header" class="header" itemscope="" itemtype="http://schema.org/WPHeader">
      <div class="header-inner"><div class="site-brand-wrapper">
  <div class="site-meta ">
    

    <div class="custom-logo-site-title">
      <a href="/" class="brand" rel="start">
        <span class="logo-line-before"><i></i></span>
        <span class="site-title">九阳的笔记本</span>
        <span class="logo-line-after"><i></i></span>
      </a>
    </div>
    
  </div>

  <div class="site-nav-toggle">
    <button aria-label="切换导航栏">
      <span class="btn-bar"></span>
      <span class="btn-bar"></span>
      <span class="btn-bar"></span>
    </button>
  </div>
</div>



<nav class="site-nav">
  
    <ul id="menu" class="menu">
      
        
        
        
          
          <li class="menu-item menu-item-home">
    <a href="/" rel="section">
      <i class="menu-item-icon fa fa-fw fa-home"></i> <br>首页</a>
  </li>
        
        
        
          
          <li class="menu-item menu-item-hexo">
    <a href="/categories/Hexo" rel="section">
      <i class="menu-item-icon fa fa-fw fa-header"></i> <br>Hexo</a>
  </li>
        
        
        
          
          <li class="menu-item menu-item-linux">
    <a href="/categories/Linux" rel="section">
      <i class="menu-item-icon fa fa-fw fa-linux"></i> <br>Linux</a>
  </li>
        
        
        
          
          <li class="menu-item menu-item-docker">
    <a href="/categories/docker" rel="section">
      <i class="menu-item-icon fa fa-fw fa-archive"></i> <br>docker</a>
  </li>
        
        
        
          
          <li class="menu-item menu-item-learn">
    <a href="/categories/learn" rel="section">
      <i class="menu-item-icon fa fa-fw fa-leanpub"></i> <br>学习</a>
  </li>
        
        
        
          
          <li class="menu-item menu-item-categories">
    <a href="/categories/" rel="section">
      <i class="menu-item-icon fa fa-fw fa-th"></i> <br>分类</a>
  </li>
        
        
        
          
          <li class="menu-item menu-item-tags">
    <a href="/tags/" rel="section">
      <i class="menu-item-icon fa fa-fw fa-tags"></i> <br>标签</a>
  </li>
        
        
        
          
          <li class="menu-item menu-item-archives">
    <a href="/archives/" rel="section">
      <i class="menu-item-icon fa fa-fw fa-archive"></i> <br>归档</a>
  </li>
        
        
        
          
          <li class="menu-item menu-item-top">
    <a href="/top/" rel="section">
      <i class="menu-item-icon fa fa-fw fa-signal"></i> <br>阅读排行</a>
  </li>
        
        
        
          
          <li class="menu-item menu-item-sitemap">
    <a href="/sitemap.xml" rel="section">
      <i class="menu-item-icon fa fa-fw fa-sitemap"></i> <br>站点地图</a>
  </li>
        
        
        
          
          <li class="menu-item menu-item-about">
    <a href="/about/" rel="section">
      <i class="menu-item-icon fa fa-fw fa-user"></i> <br>关于</a>
  </li>

      
      
        <li class="menu-item menu-item-search">
          
            <a href="javascript:;" class="popup-trigger">
          
            
              <i class="menu-item-icon fa fa-search fa-fw"></i> <br>搜索</a>
        </li>
      
    </ul>
  

  
    

  

  
    <div class="site-search">
      
  <div class="popup search-popup local-search-popup">
  <div class="local-search-header clearfix">
    <span class="search-icon">
      <i class="fa fa-search"></i>
    </span>
    <span class="popup-btn-close">
      <i class="fa fa-times-circle"></i>
    </span>
    <div class="local-search-input-wrapper">
      <input autocomplete="off" placeholder="搜索..." spellcheck="false" type="text" id="local-search-input">
    </div>
  </div>
  <div id="local-search-result"></div>
</div>



    </div>
  
</nav>



  



</div>
    </header>

    


    <main id="main" class="main">
      <div class="main-inner">
        <div class="content-wrap">
          
          <div id="content" class="content">
            

  <div id="posts" class="posts-expand">
    

  

  
  
  

  

  <article class="post post-type-normal" itemscope="" itemtype="http://schema.org/Article">
  
  
  
  <div class="post-block">
    <link itemprop="mainEntityOfPage" href="https://blog.codenote.pro/this-blog-server-docker-configuration.html">

    <span hidden itemprop="author" itemscope="" itemtype="http://schema.org/Person">
      <meta itemprop="name" content="yszar">
      <meta itemprop="description" content="学无止境！">
      <meta itemprop="image" content="/images/avatar.gif">
    </span>

    <span hidden itemprop="publisher" itemscope="" itemtype="http://schema.org/Organization">
      <meta itemprop="name" content="九阳的笔记本">
    </span>

    
      <header class="post-header">

        
        
          <h2 class="post-title" itemprop="name headline">本博客服务器docker配置
              
            
          </h2>
        

        <div class="post-meta">
          <span class="post-time">

            
            
            

            
              <span class="post-meta-item-icon">
                <i class="fa fa-calendar-o"></i>
              </span>
              
                <span class="post-meta-item-text">发表于</span>
              

              
                
              

              <time title="创建时间：2018-10-31 16:42:38" itemprop="dateCreated datePublished" datetime="2018-10-31T16:42:38+08:00">2018-10-31</time>
            

            
              

              
                
                <span class="post-meta-divider">|</span>
                

                <span class="post-meta-item-icon">
                  <i class="fa fa-calendar-check-o"></i>
                </span>
                
                  <span class="post-meta-item-text">更新于</span>
                
                <time title="修改时间：2018-11-02 00:22:00" itemprop="dateModified" datetime="2018-11-02T00:22:00+08:00">2018-11-02</time>
              
            
          </span>

          

          
            
          

          
          
             <span id="/this-blog-server-docker-configuration.html" class="leancloud_visitors" data-flag-title="本博客服务器docker配置">
               <span class="post-meta-divider">|</span>
               <span class="post-meta-item-icon">
                 <i class="fa fa-eye"></i>
               </span>
               
                 <span class="post-meta-item-text">阅读次数：</span>
               
                 <span class="leancloud-visitors-count"></span>
             </span>
          

          

          

          

        </div>
      </header>
    

    
    
    
    <div class="post-body" itemprop="articleBody">

      
      

      
        <p class="description"></p>

<p><img src="https://" alt="" style="width:100%"></p>
<a id="more"></a>
<h3 id="安装依赖"><a href="#安装依赖" class="headerlink" title="安装依赖"></a>安装依赖</h3><p>我的 VPS 系统是 Ubuntu 16.04.1 LTS，如果你使用的是其它发行版，与包管理有关的命令请自行调整。</p>
<p>首先安装依赖库和编译要用到的工具：</p>
<figure class="highlight bash"><div class="figcode"><div class="gutter"><pre><div class="line">1</div></pre></div><div class="code"><pre><div class="line">apt-get -y install autoconf libtool automake wget build-essential libpcre3 libpcre3-dev zlib1g-dev git zip unzip curl make gcc g++</div></pre></div></div></figure>
<h3 id="获取必要组件"><a href="#获取必要组件" class="headerlink" title="获取必要组件"></a>获取必要组件</h3><h4 id="nginx-ct"><a href="#nginx-ct" class="headerlink" title="nginx-ct"></a>nginx-ct</h4><p><code>nginx-ct</code> 模块用于启用 <a href="https://imququ.com/post/certificate-transparency.html" rel="external nofollow noopener noreferrer" target="_blank">Certificate Transparency</a> 功能。直接从 github 上获取源码：</p>
<pre><code>wget -O nginx-ct.zip -c https://github.com/grahamedgecombe/nginx-ct/archive/v1.3.2.zip
unzip nginx-ct.zip
</code></pre><h4 id="ngx-brotli"><a href="#ngx-brotli" class="headerlink" title="ngx_brotli"></a>ngx_brotli</h4><p>本站支持 Google 开发的 <a href="https://github.com/google/brotli" rel="external nofollow noopener noreferrer" target="_blank">Brotli</a> 压缩格式，它通过内置分析大量网页得出的字典，实现了更高的压缩比率，同时几乎不影响压缩 / 解压速度。</p>
<p>以下是让 Nginx 支持 Brotli 所需准备工作，这些工作是一次性的：</p>
<figure class="highlight bash"><div class="figcode"><div class="gutter"><pre><div class="line">1</div></pre></div><div class="code"><pre><div class="line">sudo apt-get install autoconf libtool automake</div></pre></div></div></figure>
<p>接下来获取 <a href="https://github.com/google/ngx_brotli" rel="external nofollow noopener noreferrer" target="_blank">ngx_brotli</a> 源码：</p>
<figure class="highlight bash"><div class="figcode"><div class="gutter"><pre><div class="line">1</div><div class="line">2</div><div class="line">3</div><div class="line">4</div><div class="line">5</div><div class="line">6</div></pre></div><div class="code"><pre><div class="line">git <span class="built_in">clone</span> https://github.com/google/ngx_brotli.git</div><div class="line"><span class="built_in">cd</span> ngx_brotli</div><div class="line"></div><div class="line">git submodule update --init</div><div class="line"></div><div class="line"><span class="built_in">cd</span> ../</div></pre></div></div></figure>
<h4 id="OpenSSL-1-1-1"><a href="#OpenSSL-1-1-1" class="headerlink" title="OpenSSL-1.1.1"></a>OpenSSL-1.1.1</h4><p>由于系统自带的 OpenSSL 库往往不够新，推荐在编译 Nginx 时指定 OpenSSL 源码目录，而不是使用系统自带的版本，这样更可控。</p>
<p>本站目前使用 OpenSSL 1.1.1：</p>
<figure class="highlight bash"><div class="figcode"><div class="gutter"><pre><div class="line">1</div><div class="line">2</div><div class="line">3</div><div class="line">4</div><div class="line">5</div><div class="line">6</div><div class="line">7</div><div class="line">8</div><div class="line">9</div><div class="line">10</div></pre></div><div class="code"><pre><div class="line"><span class="comment"># 下载 OpenSSL 1.1.1-pre9</span></div><div class="line">wget https://www.openssl.org/<span class="built_in">source</span>/openssl-1.1.1.tar.gz</div><div class="line">tar zxf openssl-1.1.1.tar.gz</div><div class="line"></div><div class="line"><span class="comment"># 打 TLS1.3 Draft 23,26,28 补丁</span></div><div class="line"><span class="comment"># 根据 OpenSSL 版本决定, 具体见 https://github.com/hakasenyang/openssl-patch</span></div><div class="line"><span class="built_in">cd</span> openssl-1.1.1</div><div class="line">wget https://raw.githubusercontent.com/hakasenyang/openssl-patch/master/openssl-equal-1.1.1.patch</div><div class="line">patch -p1 &lt; openssl-equal-pre9.patch</div><div class="line"><span class="built_in">cd</span> ..</div></pre></div></div></figure>
<h3 id="编译并安装-Nginx"><a href="#编译并安装-Nginx" class="headerlink" title="编译并安装 Nginx"></a>编译并安装 Nginx</h3><h4 id="Nginx-1-15-5"><a href="#Nginx-1-15-5" class="headerlink" title="Nginx 1.15.5"></a>Nginx 1.15.5</h4><figure class="highlight bash"><div class="figcode"><div class="gutter"><pre><div class="line">1</div><div class="line">2</div><div class="line">3</div></pre></div><div class="code"><pre><div class="line"><span class="comment">#下载 Nginx 1.15.5</span></div><div class="line">wget https://nginx.org/download/nginx-1.15.5.tar.gz</div><div class="line">tar zxf nginx-1.15.5.tar.gz</div></pre></div></div></figure>
<p>安装原版的 Nginx 1.15.5，少了一些好用的功能，还好有 patch，笔者在这里打了 5 个 patch，也推荐大家使用。</p>
<ul>
<li>恢复对 SPDY 协议的支持</li>
<li>支持 HTTP/2 HPACK 加密</li>
<li>支持 Dynamic TLS Record (这个强烈推荐)</li>
<li>支持 SSL_OP_PRIORITIZE_CHACHA (这个强烈推荐)</li>
<li>Fix Http2 Push Error 补丁 (推荐)</li>
</ul>
<p>这些补丁不一定适用于最新的 Nginx 已测试通过的版本请查看<a href="https://github.com/kn007/patch" rel="external nofollow noopener noreferrer" target="_blank">https://github.com/kn007/patch</a></p>
<figure class="highlight bash"><div class="figcode"><div class="gutter"><pre><div class="line">1</div><div class="line">2</div><div class="line">3</div><div class="line">4</div><div class="line">5</div><div class="line">6</div><div class="line">7</div><div class="line">8</div></pre></div><div class="code"><pre><div class="line"><span class="comment"># 打 SPDY, HTTP2 HPACK, Dynamic TLS Record, PRIORITIZE_CHACHA, Fix Http2 Push Error 补丁</span></div><div class="line"></div><div class="line"><span class="built_in">cd</span> nginx-1.15.5</div><div class="line">wget https://raw.githubusercontent.com/kn007/patch/master/nginx.patch</div><div class="line">wget https://raw.githubusercontent.com/kn007/patch/master/nginx_auto_using_PRIORITIZE_CHACHA.patch</div><div class="line">patch -p1 &lt; nginx.patch</div><div class="line">patch -p1 &lt; nginx_auto_using_PRIORITIZE_CHACHA.patch</div><div class="line"><span class="built_in">cd</span> ..</div></pre></div></div></figure>
<p>编译和安装：</p>
<figure class="highlight bash"><div class="figcode"><div class="gutter"><pre><div class="line">1</div><div class="line">2</div><div class="line">3</div><div class="line">4</div><div class="line">5</div><div class="line">6</div><div class="line">7</div><div class="line">8</div><div class="line">9</div><div class="line">10</div><div class="line">11</div><div class="line">12</div><div class="line">13</div><div class="line">14</div><div class="line">15</div><div class="line">16</div><div class="line">17</div><div class="line">18</div><div class="line">19</div><div class="line">20</div><div class="line">21</div><div class="line">22</div><div class="line">23</div><div class="line">24</div><div class="line">25</div></pre></div><div class="code"><pre><div class="line"><span class="built_in">cd</span> nginx-1.15.5</div><div class="line">./configure \</div><div class="line">        --prefix=/etc/nginx \</div><div class="line">        --sbin-path=/usr/sbin/nginx \</div><div class="line">        --conf-path=/etc/nginx/nginx.conf \</div><div class="line">        --error-log-path=/var/<span class="built_in">log</span>/nginx/error.log \</div><div class="line">        --http-log-path=/var/<span class="built_in">log</span>/nginx/access.log \</div><div class="line">        --pid-path=/var/run/nginx.pid \</div><div class="line">        --lock-path=/var/run/nginx.lock \</div><div class="line">        --http-client-body-temp-path=/var/cache/nginx/client_temp \</div><div class="line">        --http-proxy-temp-path=/var/cache/nginx/proxy_temp \</div><div class="line">        --http-fastcgi-temp-path=/var/cache/nginx/fastcgi_temp \</div><div class="line">        --http-uwsgi-temp-path=/var/cache/nginx/uwsgi_temp \</div><div class="line">        --http-scgi-temp-path=/var/cache/nginx/scgi_temp \</div><div class="line">        --add-module=../ngx_brotli \</div><div class="line">        --add-module=../nginx-ct-1.3.2 \</div><div class="line">        --with-openssl=<span class="variable">$BUILD_ROOT</span>/openssl-<span class="variable">$OPENSSL_VERSION</span> \</div><div class="line">        --with-pcre=<span class="variable">$BUILD_ROOT</span>/pcre-<span class="variable">$PCRE_VERSION</span> \</div><div class="line">        --with-zlib=<span class="variable">$BUILD_ROOT</span>/zlib-<span class="variable">$ZLIB_VERSION</span> \</div><div class="line">        --with-http_ssl_module \</div><div class="line">        --with-http_v2_module \</div><div class="line">        --with-threads \</div><div class="line"></div><div class="line">make</div><div class="line">sudo make install</div></pre></div></div></figure>
<p>除了 <code>http_v2</code> 和 <code>http_ssl</code> 这两个 HTTP/2 必备模块之外，我还额外启用了 <code>http_gzip_static</code>，需要启用哪些模块需要根据自己实际情况来决定。</p>
<h3 id="管理脚本与自启动"><a href="#管理脚本与自启动" class="headerlink" title="管理脚本与自启动"></a>管理脚本与自启动</h3><p>为了方便管理 Nginx 服务，再创建一个管理脚本：</p>
<figure class="highlight bash"><div class="figcode"><div class="gutter"><pre><div class="line">1</div></pre></div><div class="code"><pre><div class="line">sudo vim /etc/init.d/nginx</div></pre></div></div></figure>
<p>输入以下内容：</p>
<figure class="highlight bash"><div class="figcode"><div class="gutter"><pre><div class="line">1</div><div class="line">2</div><div class="line">3</div><div class="line">4</div><div class="line">5</div><div class="line">6</div><div class="line">7</div><div class="line">8</div><div class="line">9</div><div class="line">10</div><div class="line">11</div><div class="line">12</div><div class="line">13</div><div class="line">14</div><div class="line">15</div><div class="line">16</div><div class="line">17</div><div class="line">18</div><div class="line">19</div><div class="line">20</div><div class="line">21</div><div class="line">22</div><div class="line">23</div><div class="line">24</div><div class="line">25</div><div class="line">26</div><div class="line">27</div><div class="line">28</div><div class="line">29</div><div class="line">30</div><div class="line">31</div><div class="line">32</div><div class="line">33</div><div class="line">34</div><div class="line">35</div><div class="line">36</div><div class="line">37</div><div class="line">38</div><div class="line">39</div><div class="line">40</div><div class="line">41</div><div class="line">42</div><div class="line">43</div><div class="line">44</div><div class="line">45</div><div class="line">46</div><div class="line">47</div><div class="line">48</div><div class="line">49</div><div class="line">50</div><div class="line">51</div><div class="line">52</div><div class="line">53</div><div class="line">54</div><div class="line">55</div><div class="line">56</div><div class="line">57</div><div class="line">58</div><div class="line">59</div><div class="line">60</div><div class="line">61</div><div class="line">62</div><div class="line">63</div><div class="line">64</div><div class="line">65</div><div class="line">66</div><div class="line">67</div></pre></div><div class="code"><pre><div class="line"><span class="meta">#! /bin/sh</span></div><div class="line"></div><div class="line"><span class="comment">### BEGIN INIT INFO</span></div><div class="line"><span class="comment"># Provides:          nginx</span></div><div class="line"><span class="comment"># Required-Start:    $all</span></div><div class="line"><span class="comment"># Required-Stop:     $all</span></div><div class="line"><span class="comment"># Default-Start:     2 3 4 5</span></div><div class="line"><span class="comment"># Default-Stop:      0 1 6</span></div><div class="line"><span class="comment"># Short-Description: starts the nginx web server</span></div><div class="line"><span class="comment"># Description:       starts nginx using start-stop-daemon</span></div><div class="line"><span class="comment">### END INIT INFO</span></div><div class="line"></div><div class="line">PATH=/usr/<span class="built_in">local</span>/sbin:/usr/<span class="built_in">local</span>/bin:/sbin:/bin:/usr/sbin:/usr/bin</div><div class="line">DAEMON=/etc/nginx</div><div class="line">NAME=nginx</div><div class="line">DESC=nginx</div><div class="line"></div><div class="line"><span class="built_in">test</span> -x <span class="variable">$DAEMON</span> || <span class="built_in">exit</span> 0</div><div class="line"></div><div class="line"><span class="comment"># Include nginx defaults if available</span></div><div class="line"><span class="keyword">if</span> [ -f /etc/default/nginx ] ; <span class="keyword">then</span></div><div class="line">    . /etc/default/nginx</div><div class="line"><span class="keyword">fi</span></div><div class="line"></div><div class="line"><span class="built_in">set</span> -e</div><div class="line"></div><div class="line">. /lib/lsb/init-functions</div><div class="line"></div><div class="line"><span class="keyword">case</span> <span class="string">"<span class="variable">$1</span>"</span> <span class="keyword">in</span></div><div class="line">    start)</div><div class="line">    <span class="built_in">echo</span> -n <span class="string">"Starting <span class="variable">$DESC</span>: "</span></div><div class="line">    start-stop-daemon --start --quiet --pidfile /etc/nginx/logs/<span class="variable">$NAME</span>.pid \</div><div class="line">        --<span class="built_in">exec</span> <span class="variable">$DAEMON</span> -- <span class="variable">$DAEMON_OPTS</span> || <span class="literal">true</span></div><div class="line">    <span class="built_in">echo</span> <span class="string">"<span class="variable">$NAME</span>."</span></div><div class="line">    ;;</div><div class="line">    stop)</div><div class="line">    <span class="built_in">echo</span> -n <span class="string">"Stopping <span class="variable">$DESC</span>: "</span></div><div class="line">    start-stop-daemon --stop --quiet --pidfile /etc/nginx/logs/<span class="variable">$NAME</span>.pid \</div><div class="line">        --<span class="built_in">exec</span> <span class="variable">$DAEMON</span> || <span class="literal">true</span></div><div class="line">    <span class="built_in">echo</span> <span class="string">"<span class="variable">$NAME</span>."</span></div><div class="line">    ;;</div><div class="line">    restart|force-reload)</div><div class="line">    <span class="built_in">echo</span> -n <span class="string">"Restarting <span class="variable">$DESC</span>: "</span></div><div class="line">    start-stop-daemon --stop --quiet --pidfile \</div><div class="line">        /etc/nginx/logs/<span class="variable">$NAME</span>.pid --<span class="built_in">exec</span> <span class="variable">$DAEMON</span> || <span class="literal">true</span></div><div class="line">    sleep 1</div><div class="line">    start-stop-daemon --start --quiet --pidfile \</div><div class="line">        /etc/nginx/logs/<span class="variable">$NAME</span>.pid --<span class="built_in">exec</span> <span class="variable">$DAEMON</span> -- <span class="variable">$DAEMON_OPTS</span> || <span class="literal">true</span></div><div class="line">    <span class="built_in">echo</span> <span class="string">"<span class="variable">$NAME</span>."</span></div><div class="line">    ;;</div><div class="line">    reload)</div><div class="line">    <span class="built_in">echo</span> -n <span class="string">"Reloading <span class="variable">$DESC</span> configuration: "</span></div><div class="line">    start-stop-daemon --stop --signal HUP --quiet --pidfile /etc/nginx/logs/<span class="variable">$NAME</span>.pid \</div><div class="line">        --<span class="built_in">exec</span> <span class="variable">$DAEMON</span> || <span class="literal">true</span></div><div class="line">    <span class="built_in">echo</span> <span class="string">"<span class="variable">$NAME</span>."</span></div><div class="line">    ;;</div><div class="line">    status)</div><div class="line">    status_of_proc -p /etc/nginx/logs/<span class="variable">$NAME</span>.pid <span class="string">"<span class="variable">$DAEMON</span>"</span> nginx &amp;&amp; <span class="built_in">exit</span> 0 || <span class="built_in">exit</span> $?</div><div class="line">    ;;</div><div class="line">    *)</div><div class="line">    N=/etc/init.d/<span class="variable">$NAME</span></div><div class="line">    <span class="built_in">echo</span> <span class="string">"Usage: <span class="variable">$N</span> &#123;start|stop|restart|reload|force-reload|status&#125;"</span> &gt;&amp;2</div><div class="line">    <span class="built_in">exit</span> 1</div><div class="line">    ;;</div><div class="line"><span class="keyword">esac</span></div><div class="line"></div><div class="line"><span class="built_in">exit</span> 0</div></pre></div></div></figure>
<p>增加执行权限：<br><figure class="highlight bash"><div class="figcode"><div class="gutter"><pre><div class="line">1</div></pre></div><div class="code"><pre><div class="line">sudo chmod a+x /etc/init.d/nginx</div></pre></div></div></figure></p>
<p>现在管理 Nginx 只需使用以下命令即可：</p>
<figure class="highlight bash"><div class="figcode"><div class="gutter"><pre><div class="line">1</div></pre></div><div class="code"><pre><div class="line">sudo service nginx start|stop|restart|reload</div></pre></div></div></figure>
<p>如果要开机自动启动 Nginx，请执行以下命令：</p>
<figure class="highlight bash"><div class="figcode"><div class="gutter"><pre><div class="line">1</div></pre></div><div class="code"><pre><div class="line">sudo update-rc.d -f nginx defaults</div></pre></div></div></figure>
<h3 id="Nginx-全局配置"><a href="#Nginx-全局配置" class="headerlink" title="Nginx 全局配置"></a>Nginx 全局配置</h3><p>到此为止，Nginx 已经安装完毕。再来修改一下它的全局配置，打开 <code>/etc/nginx/conf/nginx.conf</code>，新增或修改以下内容：</p>
<figure class="highlight plain"><div class="figcode"><div class="gutter"><pre><div class="line">1</div><div class="line">2</div><div class="line">3</div><div class="line">4</div><div class="line">5</div><div class="line">6</div><div class="line">7</div><div class="line">8</div><div class="line">9</div><div class="line">10</div><div class="line">11</div><div class="line">12</div><div class="line">13</div><div class="line">14</div><div class="line">15</div><div class="line">16</div><div class="line">17</div><div class="line">18</div><div class="line">19</div><div class="line">20</div><div class="line">21</div><div class="line">22</div><div class="line">23</div><div class="line">24</div><div class="line">25</div><div class="line">26</div><div class="line">27</div><div class="line">28</div><div class="line">29</div><div class="line">30</div><div class="line">31</div><div class="line">32</div><div class="line">33</div><div class="line">34</div><div class="line">35</div><div class="line">36</div><div class="line">37</div></pre></div><div class="code"><pre><div class="line">http &#123;</div><div class="line">    include            mime.types;</div><div class="line">    default_type       application/octet-stream;</div><div class="line"></div><div class="line">    charset            UTF-8;</div><div class="line"></div><div class="line">    sendfile           on;</div><div class="line">    tcp_nopush         on;</div><div class="line">    tcp_nodelay        on;</div><div class="line"></div><div class="line">    keepalive_timeout  60;</div><div class="line"></div><div class="line">    #... ...#</div><div class="line"></div><div class="line">    gzip               on;</div><div class="line">    gzip_vary          on;</div><div class="line"></div><div class="line">    gzip_comp_level    6;</div><div class="line">    gzip_buffers       16 8k;</div><div class="line"></div><div class="line">    gzip_min_length    1000;</div><div class="line">    gzip_proxied       any;</div><div class="line">    gzip_disable       &quot;msie6&quot;;</div><div class="line"></div><div class="line">    gzip_http_version  1.0;</div><div class="line"></div><div class="line">    gzip_types         text/plain text/css application/json application/x-javascript text/xml application/xml application/xml+rss text/javascript application/javascript image/svg+xml;</div><div class="line"></div><div class="line">    # 如果编译时添加了 ngx_brotli 模块，需要增加 brotli 相关配置</div><div class="line">    brotli             on;</div><div class="line">    brotli_comp_level  6;</div><div class="line">    brotli_types       text/plain text/css application/json application/x-javascript text/xml application/xml application/xml+rss text/javascript application/javascript image/svg+xml;</div><div class="line"></div><div class="line">    #... ...#</div><div class="line"></div><div class="line">    include            /home/www/nginx_conf/*.conf;</div><div class="line">&#125;</div></pre></div></div></figure>
<p>最后的 <code>include</code> 用来加载我个人目录下的配置文件，这样今后创建和修改站点配置就不需要再使用 sudo 权限了。</p>
<p>要让网站支持浏览器通过 HTTP/2 访问必须先部署 HTTPS，要部署 HTTPS 必须先有合法的证书。本博客目前在用 RapidSSL 单域名证书，在 <a href="https://www.namecheap.com/security/ssl-certificates/rapidssl/rapidssl.aspx" rel="external nofollow noopener noreferrer" target="_blank">NameCheap</a> 购买。另外，我还申请了 <a href="http://www.letsencrypt.org/" rel="external nofollow noopener noreferrer" target="_blank">Let’s Encrypt</a> 的免费证书备用。一般情况下，个人使用 Let’s Encrypt 的免费证书就足够了，还可以节省一笔开销。</p>
<p>要申请 Let’s Encrypt 证书，推荐使用 <a href="https://github.com/Neilpang/acme.sh" rel="external nofollow noopener noreferrer" target="_blank">Neilpang/acme.sh</a> 这个小巧无依赖的命令行工具，或者参考我的这篇文章：<a href="https://imququ.com/post/letsencrypt-certificate.html" rel="external nofollow noopener noreferrer" target="_blank">Let’s Encrypt，免费好用的 HTTPS 证书</a>。</p>
<h3 id="WEB-站点配置"><a href="#WEB-站点配置" class="headerlink" title="WEB 站点配置"></a>WEB 站点配置</h3><p>以下是本博客站点完整配置：</p>
<figure class="highlight plain"><div class="figcode"><div class="gutter"><pre><div class="line">1</div><div class="line">2</div><div class="line">3</div><div class="line">4</div><div class="line">5</div><div class="line">6</div><div class="line">7</div><div class="line">8</div><div class="line">9</div><div class="line">10</div><div class="line">11</div><div class="line">12</div><div class="line">13</div><div class="line">14</div><div class="line">15</div><div class="line">16</div><div class="line">17</div><div class="line">18</div><div class="line">19</div><div class="line">20</div><div class="line">21</div><div class="line">22</div><div class="line">23</div><div class="line">24</div><div class="line">25</div><div class="line">26</div><div class="line">27</div><div class="line">28</div><div class="line">29</div><div class="line">30</div><div class="line">31</div><div class="line">32</div><div class="line">33</div><div class="line">34</div><div class="line">35</div><div class="line">36</div><div class="line">37</div><div class="line">38</div><div class="line">39</div><div class="line">40</div><div class="line">41</div><div class="line">42</div><div class="line">43</div><div class="line">44</div><div class="line">45</div><div class="line">46</div><div class="line">47</div><div class="line">48</div><div class="line">49</div><div class="line">50</div><div class="line">51</div><div class="line">52</div><div class="line">53</div><div class="line">54</div><div class="line">55</div><div class="line">56</div><div class="line">57</div><div class="line">58</div><div class="line">59</div><div class="line">60</div><div class="line">61</div><div class="line">62</div><div class="line">63</div><div class="line">64</div><div class="line">65</div><div class="line">66</div><div class="line">67</div><div class="line">68</div><div class="line">69</div><div class="line">70</div><div class="line">71</div><div class="line">72</div><div class="line">73</div><div class="line">74</div><div class="line">75</div><div class="line">76</div><div class="line">77</div><div class="line">78</div><div class="line">79</div><div class="line">80</div><div class="line">81</div><div class="line">82</div><div class="line">83</div><div class="line">84</div><div class="line">85</div><div class="line">86</div><div class="line">87</div><div class="line">88</div><div class="line">89</div><div class="line">90</div><div class="line">91</div><div class="line">92</div><div class="line">93</div><div class="line">94</div><div class="line">95</div><div class="line">96</div><div class="line">97</div><div class="line">98</div><div class="line">99</div><div class="line">100</div><div class="line">101</div><div class="line">102</div><div class="line">103</div><div class="line">104</div><div class="line">105</div><div class="line">106</div><div class="line">107</div><div class="line">108</div><div class="line">109</div><div class="line">110</div><div class="line">111</div><div class="line">112</div><div class="line">113</div><div class="line">114</div><div class="line">115</div><div class="line">116</div><div class="line">117</div><div class="line">118</div><div class="line">119</div><div class="line">120</div><div class="line">121</div><div class="line">122</div><div class="line">123</div><div class="line">124</div><div class="line">125</div><div class="line">126</div><div class="line">127</div><div class="line">128</div><div class="line">129</div><div class="line">130</div><div class="line">131</div><div class="line">132</div><div class="line">133</div><div class="line">134</div><div class="line">135</div><div class="line">136</div><div class="line">137</div><div class="line">138</div><div class="line">139</div><div class="line">140</div><div class="line">141</div><div class="line">142</div><div class="line">143</div><div class="line">144</div><div class="line">145</div><div class="line">146</div><div class="line">147</div><div class="line">148</div><div class="line">149</div><div class="line">150</div><div class="line">151</div><div class="line">152</div><div class="line">153</div><div class="line">154</div></pre></div><div class="code"><pre><div class="line">server &#123;</div><div class="line">    listen               443 ssl http2 fastopen=3 reuseport;</div><div class="line"></div><div class="line">    # 如果你使用了 Cloudflare 的 HTTP/2 + SPDY 补丁，记得加上 spdy</div><div class="line">    # listen               443 ssl http2 spdy fastopen=3 reuseport;</div><div class="line"></div><div class="line">    server_name          www.imququ.com imququ.com;</div><div class="line">    server_tokens        off;</div><div class="line"></div><div class="line">    include              /home/jerry/www/nginx_conf/ip.blacklist;</div><div class="line"></div><div class="line">    # https://imququ.com/post/certificate-transparency.html#toc-2</div><div class="line">    ssl_ct               on;</div><div class="line">    ssl_ct_static_scts   /home/jerry/www/scts;</div><div class="line"></div><div class="line">    # 中间证书 + 站点证书</div><div class="line">    ssl_certificate      /home/jerry/www/ssl/chained.pem;</div><div class="line"></div><div class="line">    # 创建 CSR 文件时用的密钥</div><div class="line">    ssl_certificate_key  /home/jerry/www/ssl/domain.key;</div><div class="line"></div><div class="line">    # openssl dhparam -out dhparams.pem 2048</div><div class="line">    # https://weakdh.org/sysadmin.html</div><div class="line">    ssl_dhparam          /home/jerry/www/ssl/dhparams.pem;</div><div class="line"></div><div class="line">    # https://github.com/cloudflare/sslconfig/blob/master/conf</div><div class="line">    ssl_ciphers                EECDH+CHACHA20:EECDH+CHACHA20-draft:EECDH+AES128:RSA+AES128:EECDH+AES256:RSA+AES256:EECDH+3DES:RSA+3DES:!MD5;</div><div class="line"></div><div class="line">    # 如果启用了 RSA + ECDSA 双证书，Cipher Suite 可以参考以下配置：</div><div class="line">    # ssl_ciphers              EECDH+CHACHA20:EECDH+CHACHA20-draft:EECDH+ECDSA+AES128:EECDH+aRSA+AES128:RSA+AES128:EECDH+ECDSA+AES256:EECDH+aRSA+AES256:RSA+AES256:EECDH+ECDSA+3DES:EECDH+aRSA+3DES:RSA+3DES:!MD5;</div><div class="line"></div><div class="line">    ssl_prefer_server_ciphers  on;</div><div class="line"></div><div class="line">    ssl_protocols              TLSv1 TLSv1.1 TLSv1.2;</div><div class="line"></div><div class="line">    ssl_session_cache          shared:SSL:50m;</div><div class="line">    ssl_session_timeout        1d;</div><div class="line"></div><div class="line">    ssl_session_tickets        on;</div><div class="line"></div><div class="line">    # openssl rand 48 &gt; session_ticket.key</div><div class="line">    # 单机部署可以不指定 ssl_session_ticket_key</div><div class="line">    ssl_session_ticket_key     /home/jerry/www/ssl/session_ticket.key;</div><div class="line"></div><div class="line">    ssl_stapling               on;</div><div class="line">    ssl_stapling_verify        on;</div><div class="line"></div><div class="line">    # 根证书 + 中间证书</div><div class="line">    # https://imququ.com/post/why-can-not-turn-on-ocsp-stapling.html</div><div class="line">    ssl_trusted_certificate    /home/jerry/www/ssl/full_chained.pem;</div><div class="line"></div><div class="line">    resolver                   114.114.114.114 valid=300s;</div><div class="line">    resolver_timeout           10s;</div><div class="line"></div><div class="line">    access_log                 /home/jerry/www/nginx_log/imququ_com.log;</div><div class="line"></div><div class="line">    if ($request_method !~ ^(GET|HEAD|POST|OPTIONS)$ ) &#123;</div><div class="line">        return           444;</div><div class="line">    &#125;</div><div class="line"></div><div class="line">    if ($host != &apos;imququ.com&apos; ) &#123;</div><div class="line">        rewrite          ^/(.*)$  https://imququ.com/$1 permanent;</div><div class="line">    &#125;</div><div class="line"></div><div class="line">    location ~* (robots\.txt|favicon\.ico|crossdomain\.xml|google4c90d18e696bdcf8\.html|BingSiteAuth\.xml)$ &#123;</div><div class="line">        root             /home/jerry/www/imququ.com/www/static;</div><div class="line">        expires          1d;</div><div class="line">    &#125;</div><div class="line"></div><div class="line">    location ^~ /static/uploads/ &#123;</div><div class="line">        root             /home/jerry/www/imququ.com/www;</div><div class="line">        add_header       Access-Control-Allow-Origin *;</div><div class="line"></div><div class="line">        set              $expires_time max;</div><div class="line"></div><div class="line">        valid_referers   blocked none server_names *.qgy18.com *.inoreader.com feedly.com *.feedly.com www.udpwork.com theoldreader.com digg.com *.feiworks.com *.newszeit.com r.mail.qq.com yuedu.163.com *.w3ctech.com;</div><div class="line">        if ($invalid_referer) &#123;</div><div class="line">            set          $expires_time -1;</div><div class="line">            return       403;</div><div class="line">        &#125;</div><div class="line"></div><div class="line">        expires          $expires_time;</div><div class="line">    &#125;</div><div class="line"></div><div class="line">    location ^~ /static/ &#123;</div><div class="line">        root             /home/jerry/www/imququ.com/www;</div><div class="line">        add_header       Access-Control-Allow-Origin *;</div><div class="line">        expires          max;</div><div class="line">    &#125;</div><div class="line"></div><div class="line">    location ^~ /admin/ &#123;</div><div class="line">        proxy_http_version       1.1;</div><div class="line"></div><div class="line">        add_header               Strict-Transport-Security &quot;max-age=31536000; includeSubDomains; preload&quot;;</div><div class="line"></div><div class="line">        # DENY 将完全不允许页面被嵌套，可能会导致一些异常。如果遇到这样的问题，建议改成 SAMEORIGIN</div><div class="line">        # https://imququ.com/post/web-security-and-response-header.html#toc-1</div><div class="line">        add_header               X-Frame-Options DENY;</div><div class="line"></div><div class="line">        add_header               X-Content-Type-Options nosniff;</div><div class="line"></div><div class="line">        proxy_set_header         X-Via            QingDao.Aliyun;</div><div class="line">        proxy_set_header         Connection       &quot;&quot;;</div><div class="line">        proxy_set_header         Host             imququ.com;</div><div class="line">        proxy_set_header         X-Real_IP        $remote_addr;</div><div class="line">        proxy_set_header         X-Forwarded-For  $proxy_add_x_forwarded_for;</div><div class="line"></div><div class="line">        proxy_pass               http://127.0.0.1:9095;</div><div class="line">    &#125;</div><div class="line"></div><div class="line">    location / &#123;</div><div class="line">        proxy_http_version       1.1;</div><div class="line"></div><div class="line">        add_header               Strict-Transport-Security &quot;max-age=31536000; includeSubDomains; preload&quot;;</div><div class="line">        add_header               X-Frame-Options deny;</div><div class="line">        add_header               X-Content-Type-Options nosniff;</div><div class="line">        add_header               Content-Security-Policy &quot;default-src &apos;none&apos;; script-src &apos;unsafe-inline&apos; &apos;unsafe-eval&apos; blob: https:; img-src data: https: http://ip.qgy18.com; style-src &apos;unsafe-inline&apos; https:; child-src https:; connect-src &apos;self&apos; https://translate.googleapis.com; frame-src https://disqus.com https://www.slideshare.net&quot;;</div><div class="line">        add_header               Public-Key-Pins &apos;pin-sha256=&quot;YLh1dUR9y6Kja30RrAn7JKnbQG/uEtLMkBgFF2Fuihg=&quot;; pin-sha256=&quot;aef6IF2UF6jNEwA2pNmP7kpgT6NFSdt7Tqf5HzaIGWI=&quot;; max-age=2592000; includeSubDomains&apos;;</div><div class="line">        add_header               Cache-Control no-cache;</div><div class="line"></div><div class="line">        proxy_ignore_headers     Set-Cookie;</div><div class="line"></div><div class="line">        proxy_hide_header        Vary;</div><div class="line">        proxy_hide_header        X-Powered-By;</div><div class="line"></div><div class="line">        proxy_set_header         X-Via            QingDao.Aliyun;</div><div class="line">        proxy_set_header         Connection       &quot;&quot;;</div><div class="line">        proxy_set_header         Host             imququ.com;</div><div class="line">        proxy_set_header         X-Real_IP        $remote_addr;</div><div class="line">        proxy_set_header         X-Forwarded-For  $proxy_add_x_forwarded_for;</div><div class="line"></div><div class="line">        proxy_pass               http://127.0.0.1:9095;</div><div class="line">    &#125;</div><div class="line">&#125;</div><div class="line"></div><div class="line">server &#123;</div><div class="line">    server_name       www.imququ.com imququ.com;</div><div class="line">    server_tokens     off;</div><div class="line"></div><div class="line">    access_log        /dev/null;</div><div class="line"></div><div class="line">    if ($request_method !~ ^(GET|HEAD|POST)$ ) &#123;</div><div class="line">        return        444;</div><div class="line">    &#125;</div><div class="line"></div><div class="line">    location ^~ /.well-known/acme-challenge/ &#123;</div><div class="line">        alias         /home/jerry/www/challenges/;</div><div class="line">        try_files     $uri =404;</div><div class="line">    &#125;</div><div class="line"></div><div class="line">    location / &#123;</div><div class="line">        rewrite       ^/(.*)$ https://imququ.com/$1 permanent;</div><div class="line">    &#125;</div><div class="line">&#125;</div></pre></div></div></figure>
<h3 id="日志自动切分"><a href="#日志自动切分" class="headerlink" title="日志自动切分"></a>日志自动切分</h3><p>上一节中，我在 Nginx 的站点配置中通过 <code>access_log</code> 指定了访问日志的存放位置。Nginx 启动后，会持续往这个文件写入访问日志。如果网站访问量很大，最好能按照指定大小或者时间间隔切分日志，便于后期管理和排查问题。</p>
<p>虽然本站访问量不大，但我也使用了 <code>logrotate</code> 工具对访问日志进行了按天切分。</p>
<p>大多数 Linux 发行版都内置了 <code>logrotate</code>，只需新建一个配置文件即可，例如：</p>
<figure class="highlight bash"><div class="figcode"><div class="gutter"><pre><div class="line">1</div></pre></div><div class="code"><pre><div class="line">sudo vim /etc/logrotate.d/nginx</div></pre></div></div></figure>
<figure class="highlight plain"><div class="figcode"><div class="gutter"><pre><div class="line">1</div><div class="line">2</div><div class="line">3</div><div class="line">4</div><div class="line">5</div><div class="line">6</div><div class="line">7</div><div class="line">8</div><div class="line">9</div><div class="line">10</div><div class="line">11</div><div class="line">12</div><div class="line">13</div><div class="line">14</div></pre></div><div class="code"><pre><div class="line">/home/jerry/www/nginx_log/*.log &#123;</div><div class="line">    su root root</div><div class="line">    daily</div><div class="line">    rotate 5</div><div class="line">    missingok</div><div class="line">    notifempty</div><div class="line">    sharedscripts</div><div class="line">    dateext</div><div class="line">    postrotate</div><div class="line">        if [ -f /usr/local/nginx/logs/nginx.pid ]; then</div><div class="line">            kill -USR1 `cat /usr/local/nginx/logs/nginx.pid`</div><div class="line">        fi</div><div class="line">    endscript</div><div class="line">&#125;</div></pre></div></div></figure>
<p>配置中具体指令的含义可以查看<a href="http://www.linuxcommand.org/man_pages/logrotate8.html" rel="external nofollow noopener noreferrer" target="_blank">手册</a>。配置好之后，可以手动执行一下，看是否正常：</p>
<figure class="highlight bash"><div class="figcode"><div class="gutter"><pre><div class="line">1</div></pre></div><div class="code"><pre><div class="line">sudo /usr/sbin/logrotate -f /etc/logrotate.d/nginx</div></pre></div></div></figure>
<p>如果一切无误，后续 Nginx 的访问日志就会自动按天切分，并以年月日做为文件后缀，一目了然。</p>
<p>在我的 Ubuntu 16.04.1 LTS 上，<code>/etc/logrotate.d/</code> 目录中的日志切分任务会由 <code>/etc/cron.daily/logrotate</code> 来确保每天执行一次。查看 <code>/etc/crontab</code> 会发现 <code>cron.daily</code> 任务会在每天 6:25 执行，这就是 logrotate 每天切分日志的时机。</p>
<p>如果想要让日志正好在零点被切分，可以修改 <code>cron.daily</code> 的执行时机，也可以把自己的 logrotate 配置文件放在 <code>/etc/logrotate.d/</code> 之外，再手动配置 crontab 规则。</p>
<h3 id="安全测试和评分"><a href="#安全测试和评分" class="headerlink" title="安全测试和评分"></a>安全测试和评分</h3><p>一切妥当后，推荐使用以下两个在线服务来检测站点 HTTPS 配置：</p>
<p><strong>1）Qualys SSL Labs’s SSL Server Test</strong></p>
<p>测试地址：<a href="https://www.ssllabs.com/ssltest/index.html" rel="external nofollow noopener noreferrer" target="_blank">https://www.ssllabs.com/ssltest/index.html</a>，以下是本博客测试结果截图：</p>
<p><a href="https://ssllabs.com/ssltest/analyze.html?d=imququ.com" rel="external nofollow noopener noreferrer" target="_blank">查看完整测试结果 »</a></p>
<p>注：如果选择使用 Cloudflare 的 HTTP/2 + SPDY 修改版，记得在站点配置中加上 <code>spdy</code>，这样才能增加对 SPDY 协议的支持。如果配置正确，在这个工具的 NPN 信息中可以看到类似这样的结果：<code>Yes h2 spdy/3.1 http/1.1</code>。</p>
<p><strong>2）HTTP Security Report</strong></p>
<p>测试地址：<a href="https://httpsecurityreport.com/" rel="external nofollow noopener noreferrer" target="_blank">https://httpsecurityreport.com/</a>，以下是本博客测试结果截图：</p>
<p><a href="https://httpsecurityreport.com/?report=imququ.com" rel="external nofollow noopener noreferrer" target="_blank">查看完整测试结果 »</a></p>
<h3 id="Docker"><a href="#Docker" class="headerlink" title="Docker"></a>Docker</h3><p>为使用docker的同学给出我的配置</p>
<h4 id="Nginx的Dockerfile"><a href="#Nginx的Dockerfile" class="headerlink" title="Nginx的Dockerfile"></a>Nginx的Dockerfile</h4><figure class="highlight dockerfile"><div class="figcode"><div class="gutter"><pre><div class="line">1</div><div class="line">2</div><div class="line">3</div><div class="line">4</div><div class="line">5</div><div class="line">6</div><div class="line">7</div><div class="line">8</div><div class="line">9</div><div class="line">10</div><div class="line">11</div><div class="line">12</div><div class="line">13</div><div class="line">14</div><div class="line">15</div><div class="line">16</div><div class="line">17</div><div class="line">18</div><div class="line">19</div><div class="line">20</div><div class="line">21</div><div class="line">22</div><div class="line">23</div><div class="line">24</div><div class="line">25</div><div class="line">26</div><div class="line">27</div><div class="line">28</div><div class="line">29</div><div class="line">30</div><div class="line">31</div><div class="line">32</div><div class="line">33</div><div class="line">34</div><div class="line">35</div><div class="line">36</div><div class="line">37</div><div class="line">38</div><div class="line">39</div><div class="line">40</div><div class="line">41</div><div class="line">42</div><div class="line">43</div><div class="line">44</div><div class="line">45</div><div class="line">46</div><div class="line">47</div><div class="line">48</div><div class="line">49</div><div class="line">50</div><div class="line">51</div><div class="line">52</div><div class="line">53</div><div class="line">54</div><div class="line">55</div><div class="line">56</div><div class="line">57</div><div class="line">58</div><div class="line">59</div><div class="line">60</div><div class="line">61</div><div class="line">62</div><div class="line">63</div><div class="line">64</div><div class="line">65</div><div class="line">66</div><div class="line">67</div><div class="line">68</div><div class="line">69</div><div class="line">70</div><div class="line">71</div><div class="line">72</div><div class="line">73</div><div class="line">74</div><div class="line">75</div><div class="line">76</div><div class="line">77</div></pre></div><div class="code"><pre><div class="line"><span class="keyword">FROM</span> ubuntu:<span class="number">16.04</span></div><div class="line"></div><div class="line"><span class="keyword">MAINTAINER</span> yszar <span class="string">"www.codenote.pro"</span></div><div class="line"></div><div class="line"><span class="comment">#定义变量</span></div><div class="line"><span class="keyword">ENV</span> NGINX_VERSION <span class="number">1.15</span>.<span class="number">5</span></div><div class="line"><span class="keyword">ENV</span> OPENSSL_VERSION <span class="number">1.1</span>.<span class="number">1</span></div><div class="line"><span class="keyword">ENV</span> PCRE_VERSION <span class="number">8.42</span></div><div class="line"><span class="keyword">ENV</span> ZLIB_VERSION <span class="number">1.2</span>.<span class="number">11</span></div><div class="line"><span class="keyword">ENV</span> BUILD_ROOT /usr/local/src/nginx</div><div class="line"></div><div class="line"><span class="comment"># 这里为了加快构建速度，使用了阿里云的安装源</span></div><div class="line"><span class="keyword">RUN</span><span class="bash"> cp /etc/apt/sources.list /etc/apt/sources.list.bak \</span></div><div class="line"><span class="bash">        &amp;&amp; sed -i <span class="string">"s/archive\.ubuntu\.com/mirrors\.aliyun\.com/g"</span> /etc/apt/sources.list \</span></div><div class="line"><span class="bash">        &amp;&amp; apt-get update \</span></div><div class="line"><span class="bash">        &amp;&amp; apt-get -y install autoconf libtool automake wget build-essential libpcre3 libpcre3-dev zlib1g-dev git zip unzip curl make gcc g++ \</span></div><div class="line"><span class="bash">        &amp;&amp; mkdir -p <span class="variable">$BUILD_ROOT</span> \</span></div><div class="line"><span class="bash">        &amp;&amp; <span class="built_in">cd</span> <span class="variable">$BUILD_ROOT</span> \</span></div><div class="line"><span class="bash">        &amp;&amp; curl https://ftp.pcre.org/pub/pcre/pcre-<span class="variable">$PCRE_VERSION</span>.zip -o <span class="variable">$BUILD_ROOT</span>/pcre-<span class="variable">$PCRE_VERSION</span>.zip \</span></div><div class="line"><span class="bash">        &amp;&amp; curl https://www.openssl.org/<span class="built_in">source</span>/openssl-<span class="variable">$OPENSSL_VERSION</span>.tar.gz -o <span class="variable">$BUILD_ROOT</span>/openssl-<span class="variable">$OPENSSL_VERSION</span>.tar.gz \</span></div><div class="line"><span class="bash">        &amp;&amp; curl http://www.zlib.net/zlib-<span class="variable">$ZLIB_VERSION</span>.tar.gz -o <span class="variable">$BUILD_ROOT</span>/zlib-<span class="variable">$ZLIB_VERSION</span>.tar.gz \</span></div><div class="line"><span class="bash">        &amp;&amp; curl https://nginx.org/download/nginx-<span class="variable">$NGINX_VERSION</span>.tar.gz -o <span class="variable">$BUILD_ROOT</span>/nginx-<span class="variable">$NGINX_VERSION</span>.tar.gz \</span></div><div class="line"><span class="bash">        &amp;&amp; wget -O nginx-ct.zip -c https://github.com/grahamedgecombe/nginx-ct/archive/v1.3.2.zip \</span></div><div class="line"><span class="bash">        &amp;&amp; unzip nginx-ct.zip \</span></div><div class="line"><span class="bash">        &amp;&amp; tar vxzf nginx-<span class="variable">$NGINX_VERSION</span>.tar.gz \</span></div><div class="line"><span class="bash">        &amp;&amp; unzip pcre-<span class="variable">$PCRE_VERSION</span>.zip \</span></div><div class="line"><span class="bash">        &amp;&amp; git <span class="built_in">clone</span> https://github.com/google/ngx_brotli.git \</span></div><div class="line"><span class="bash">        &amp;&amp; <span class="built_in">cd</span> ngx_brotli \</span></div><div class="line"><span class="bash">        &amp;&amp; git submodule update --init \</span></div><div class="line"><span class="bash">        &amp;&amp; <span class="built_in">cd</span> ../ \</span></div><div class="line"><span class="bash">        &amp;&amp; tar vxfz zlib-<span class="variable">$ZLIB_VERSION</span>.tar.gz \</span></div><div class="line"><span class="bash">        &amp;&amp; tar vxfz openssl-<span class="variable">$OPENSSL_VERSION</span>.tar.gz \</span></div><div class="line"><span class="bash">        &amp;&amp; <span class="built_in">cd</span> openssl-<span class="variable">$OPENSSL_VERSION</span> \</span></div><div class="line"><span class="bash">        &amp;&amp; wget https://raw.githubusercontent.com/hakasenyang/openssl-patch/master/openssl-equal-1.1.1.patch \</span></div><div class="line"><span class="bash">        &amp;&amp; patch -p1 &lt; openssl-equal-1.1.1.patch \</span></div><div class="line"><span class="bash">        &amp;&amp; <span class="built_in">cd</span> ../ \</span></div><div class="line"><span class="bash">        &amp;&amp; <span class="built_in">cd</span> nginx-<span class="variable">$NGINX_VERSION</span> \</span></div><div class="line"><span class="bash">        &amp;&amp; wget https://raw.githubusercontent.com/kn007/patch/master/nginx.patch \</span></div><div class="line"><span class="bash">        &amp;&amp; wget https://raw.githubusercontent.com/kn007/patch/master/nginx_auto_using_PRIORITIZE_CHACHA.patch \</span></div><div class="line"><span class="bash">        &amp;&amp; patch -p1 &lt; nginx.patch \</span></div><div class="line"><span class="bash">        &amp;&amp; patch -p1 &lt; nginx_auto_using_PRIORITIZE_CHACHA.patch \</span></div><div class="line"><span class="bash">        &amp;&amp; BUILD_CONFIG=<span class="string">"\</span></span></div><div class="line"><span class="bash">            --prefix=/etc/nginx \</span></div><div class="line"><span class="bash">            --sbin-path=/usr/sbin/nginx \</span></div><div class="line"><span class="bash">            --conf-path=/etc/nginx/nginx.conf \</span></div><div class="line"><span class="bash">            --error-log-path=/var/<span class="built_in">log</span>/nginx/error.log \</span></div><div class="line"><span class="bash">            --http-log-path=/var/<span class="built_in">log</span>/nginx/access.log \</span></div><div class="line"><span class="bash">            --pid-path=/var/run/nginx.pid \</span></div><div class="line"><span class="bash">            --lock-path=/var/run/nginx.lock \</span></div><div class="line"><span class="bash">            --http-client-body-temp-path=/var/cache/nginx/client_temp \</span></div><div class="line"><span class="bash">            --http-proxy-temp-path=/var/cache/nginx/proxy_temp \</span></div><div class="line"><span class="bash">            --http-fastcgi-temp-path=/var/cache/nginx/fastcgi_temp \</span></div><div class="line"><span class="bash">            --http-uwsgi-temp-path=/var/cache/nginx/uwsgi_temp \</span></div><div class="line"><span class="bash">            --http-scgi-temp-path=/var/cache/nginx/scgi_temp \</span></div><div class="line"><span class="bash">            --add-module=../ngx_brotli \</span></div><div class="line"><span class="bash">            --add-module=../nginx-ct-1.3.2 \</span></div><div class="line"><span class="bash">            --with-openssl=<span class="variable">$BUILD_ROOT</span>/openssl-<span class="variable">$OPENSSL_VERSION</span> \</span></div><div class="line"><span class="bash">            --with-pcre=<span class="variable">$BUILD_ROOT</span>/pcre-<span class="variable">$PCRE_VERSION</span> \</span></div><div class="line"><span class="bash">            --with-zlib=<span class="variable">$BUILD_ROOT</span>/zlib-<span class="variable">$ZLIB_VERSION</span> \</span></div><div class="line"><span class="bash">            --with-http_ssl_module \</span></div><div class="line"><span class="bash">            --with-http_v2_module \</span></div><div class="line"><span class="bash">            --with-threads \</span></div><div class="line"><span class="bash">            <span class="string">" \</span></span></div><div class="line"><span class="bash">        &amp;&amp; mkdir -p /var/cache/nginx \</span></div><div class="line"><span class="bash">        &amp;&amp; ./configure <span class="variable">$BUILD_CONFIG</span> \</span></div><div class="line"><span class="bash">        &amp;&amp; make &amp;&amp; make install \</span></div><div class="line"><span class="bash">        &amp;&amp; rm -rf <span class="variable">$BUILD_ROOT</span> \</span></div><div class="line"><span class="bash">        &amp;&amp; apt-get -y remove zip unzip curl wget make gcc g++ \</span></div><div class="line"><span class="bash">        &amp;&amp; apt-get -y autoremove \</span></div><div class="line"><span class="bash">        &amp;&amp; rm -rf /var/lib/apt/lists/* \</span></div><div class="line"><span class="bash">        &amp;&amp; cp /etc/apt/sources.list.bak /etc/apt/sources.list \</span></div><div class="line"><span class="bash">        &amp;&amp; ln -sf /dev/stdout /var/<span class="built_in">log</span>/nginx/access.log \</span></div><div class="line"><span class="bash">        &amp;&amp; ln -sf /dev/stderr /var/<span class="built_in">log</span>/nginx/error.log</span></div><div class="line"><span class="bash"></span></div><div class="line"><span class="bash">EXPOSE 80 443</span></div><div class="line"><span class="bash"></span></div><div class="line"><span class="bash">CMD [<span class="string">"nginx"</span>, <span class="string">"-g"</span>, <span class="string">"daemon off;"</span>]</span></div></pre></div></div></figure>
<hr>
      
    </div>

    
      


    

    
    
    
    
    <div>
        
        <div>
    
        <div style="text-align:center;color: #ccc;font-size:14px;">-------------本文结束<i class="fa fa-paw"></i>感谢您的阅读-------------</div>
    
</div>
        
    </div>
    
    <div>
          
            
<div class="my_post_copyright">
  <script src="//cdn.bootcss.com/clipboard.js/1.5.10/clipboard.min.js"></script>
  
  <!-- JS库 sweetalert 可修改路径 -->
  <script src="https://cdn.bootcss.com/jquery/2.0.0/jquery.min.js"></script>
  <script src="https://unpkg.com/sweetalert/dist/sweetalert.min.js"></script>
  <p><span>本文标题:</span><a href="/this-blog-server-docker-configuration.html">本博客服务器docker配置</a></p>
  <p><span>文章作者:</span><a href="/" title="访问 yszar 的个人博客">yszar</a></p>
  <p><span>发布时间:</span>2018年10月31日 - 16:10</p>
  <p><span>最后更新:</span>2018年11月02日 - 00:11</p>
  <p><span>原始链接:</span><a href="/this-blog-server-docker-configuration.html" title="本博客服务器docker配置">https://blog.codenote.pro/this-blog-server-docker-configuration.html</a>
    <span class="copy-path" title="点击复制文章链接"><i class="fas fa-copy" data-clipboard-text="https://blog.codenote.pro/this-blog-server-docker-configuration.html" aria-label="复制成功！"></i></span>
  </p>
  <p><span>许可协议:</span><i class="fa fa-creative-commons"></i> <a rel="external nofollow noopener noreferrer" href="https://creativecommons.org/licenses/by-nc-nd/4.0/" target="_blank" title="Attribution-NonCommercial-NoDerivatives 4.0 International (CC BY-NC-ND 4.0)">署名-非商业性使用-禁止演绎 4.0 国际</a> 转载请保留原文链接及作者。</p>  
</div>
<script> 
    var clipboard = new Clipboard('.fa-clipboard');
      $(".fa-clipboard").click(function(){
      clipboard.on('success', function(){
        swal({   
          title: "",   
          text: '复制成功',
          icon: "success", 
          showConfirmButton: true
          });
        });
    });  
</script>


          
    </div>

    
      <div>
        <div id="wechat_subscriber" style="display: block; padding: 10px 0; margin: 20px auto; width: 100%; text-align: center">
    <img id="wechat_subscriber_qcode" src="/uploads/wechat-qcode.jpg" alt="yszar wechat" style="width: 200px; max-width: 100%;">
    <div>欢迎您扫一扫上面的微信公众号，订阅我的博客！</div>
</div>

      </div>
    

    
      <div>
        <div style="padding: 10px 0; margin: 20px auto; width: 90%; text-align: center;">
  <div>坚持原创技术分享，您的支持将鼓励我继续创作！</div>
  <button id="rewardButton" disable="enable" onclick="var qr = document.getElementById('QR'); if (qr.style.display === 'none') {qr.style.display='block';} else {qr.style.display='none'}">
    <span>打赏</span>
  </button>
  <div id="QR" style="display: none;">

    
      <div id="wechat" style="display: inline-block">
        <img id="wechat_qr" src="/uploads/wxfk.png" alt="yszar 微信支付">
        <p>微信支付</p>
      </div>
    

    
      <div id="alipay" style="display: inline-block">
        <img id="alipay_qr" src="/uploads/zfbfk.png" alt="yszar 支付宝">
        <p>支付宝</p>
      </div>
    

    

  </div>
</div>

      </div>
    

    

    <footer class="post-footer">
      
        <div class="post-tags">
          
            <a href="/tags/docker/" rel="tag"><i class="fa fa-tag"></i> docker</a>
          
            <a href="/tags/服务器/" rel="tag"><i class="fa fa-tag"></i> 服务器</a>
          
        </div>
      

      
      
        <div class="post-widgets">
        
          <div class="wp_rating">
          <div style="color: rgba(0, 0, 0, 0.75); font-size:13px; letter-spacing:3px">(&gt;看完记得五星好评哦亲&lt;)</div>
            <div id="wpac-rating"></div>
          </div>
        

        

        
        </div>
      
      

      
        <div class="post-nav">
          <div class="post-nav-next post-nav-item">
            
            
              
              <a href="/python-get-the-current-directory-path-and-superior.html" rel="prev" title="python获取当前目录路径和上级路径">
                
                <i class="fa fa-chevron-left"></i> python获取当前目录路径和上级路径
              </a>
            
          </div>

          <span class="post-nav-divider"></span>

          <div class="post-nav-prev post-nav-item">
            
            
              
              <a href="/the-docker-environment-opens-up-hexo-typecho-wechat-public-account.html" rel="next" title="docker环境打通Hexo Typecho 微信公众号">
                
                docker环境打通Hexo Typecho 微信公众号 <i class="fa fa-chevron-right"></i>
              </a>
            
          </div>
        </div>
      

      
      
    </footer>
  </div>
  
  
  
  </article>


  </div>


          </div>
          

  
       <div id="gitalk-container"></div>
       <link rel="stylesheet" href="https://unpkg.com/gitalk/dist/gitalk.css">
  



        </div>
        
          
  
  <div class="sidebar-toggle">
    <div class="sidebar-toggle-line-wrap">
      <span class="sidebar-toggle-line sidebar-toggle-line-first"></span>
      <span class="sidebar-toggle-line sidebar-toggle-line-middle"></span>
      <span class="sidebar-toggle-line sidebar-toggle-line-last"></span>
    </div>
  </div>

  <aside id="sidebar" class="sidebar">
    
    <div class="sidebar-inner">

      

      
        <ul class="sidebar-nav motion-element">
          <li class="sidebar-nav-toc sidebar-nav-active" data-target="post-toc-wrap">
            文章目录
          </li>
          <li class="sidebar-nav-overview" data-target="site-overview-wrap">
            站点概览
          </li>
        </ul>
      

      <section class="site-overview-wrap sidebar-panel">
        <div class="site-overview">
          <div class="site-author motion-element" itemprop="author" itemscope="" itemtype="http://schema.org/Person">
            
              <p class="site-author-name" itemprop="name">yszar</p>
              <p class="site-description motion-element" itemprop="description">学无止境！</p>
          </div>

          
            <nav class="site-state motion-element">
              
                <div class="site-state-item site-state-posts">
                
                  <a href="/archives/">
                
                    <span class="site-state-item-count">21</span>
                    <span class="site-state-item-name">日志</span>
                  </a>
                </div>
              

              
                
                
                <div class="site-state-item site-state-categories">
                  <a href="/categories/index.html">
                    
                    
                      
                    
                      
                    
                      
                    
                      
                    
                      
                    
                    <span class="site-state-item-count">5</span>
                    <span class="site-state-item-name">分类</span>
                  </a>
                </div>
              

              
                
                
                <div class="site-state-item site-state-tags">
                  <a href="/tags/index.html">
                    
                    
                      
                    
                      
                    
                      
                    
                      
                    
                      
                    
                      
                    
                      
                    
                      
                    
                      
                    
                      
                    
                      
                    
                      
                    
                      
                    
                      
                    
                      
                    
                      
                    
                      
                    
                      
                    
                      
                    
                      
                    
                      
                    
                      
                    
                      
                    
                      
                    
                      
                    
                      
                    
                      
                    
                      
                    
                      
                    
                      
                    
                      
                    
                      
                    
                      
                    
                      
                    
                      
                    
                      
                    
                      
                    
                      
                    
                      
                    
                      
                    
                      
                    
                      
                    
                    <span class="site-state-item-count">42</span>
                    <span class="site-state-item-name">标签</span>
                  </a>
                </div>
              
            </nav>
          

          
            <div class="feed-link motion-element">
              <a href="/atom.xml" rel="alternate">
                <i class="fa fa-rss"></i>
                RSS
              </a>
            </div>
          

          
            <div class="links-of-author motion-element">
              
                <span class="links-of-author-item">
                  <a href="https://github.com/yszar" target="_blank" title="GitHub" rel="external nofollow noopener noreferrer"><i class="fa fa-fw fa-github"></i>GitHub</a>
                  
                </span>
              
                <span class="links-of-author-item">
                  <a href="mailto:yszar@vip.qq.com" target="_blank" title="E-Mail" rel="external nofollow noopener noreferrer"><i class="fa fa-fw fa-envelope"></i>E-Mail</a>
                  
                </span>
              
            </div>
          

          
          
            <div class="cc-license motion-element" itemprop="license">
              <a href="https://creativecommons.org/licenses/by-nc-sa/4.0/" class="cc-opacity" target="_blank" rel="external nofollow noopener noreferrer">
                <img src="/images/cc-by-nc-sa.svg" alt="Creative Commons">
              </a>
            </div>
          

          
          

          
            
          
          
        </div>
      </section>

      
      <!--noindex-->
        <section class="post-toc-wrap motion-element sidebar-panel sidebar-panel-active">
          <div class="post-toc">

            
              
            

            
              <div class="post-toc-content"><ol class="nav"><li class="nav-item nav-level-3"><a class="nav-link" href="#安装依赖"><span class="nav-number">1.</span> <span class="nav-text">安装依赖</span></a></li><li class="nav-item nav-level-3"><a class="nav-link" href="#获取必要组件"><span class="nav-number">2.</span> <span class="nav-text">获取必要组件</span></a><ol class="nav-child"><li class="nav-item nav-level-4"><a class="nav-link" href="#nginx-ct"><span class="nav-number">2.1.</span> <span class="nav-text">nginx-ct</span></a></li><li class="nav-item nav-level-4"><a class="nav-link" href="#ngx-brotli"><span class="nav-number">2.2.</span> <span class="nav-text">ngx_brotli</span></a></li><li class="nav-item nav-level-4"><a class="nav-link" href="#OpenSSL-1-1-1"><span class="nav-number">2.3.</span> <span class="nav-text">OpenSSL-1.1.1</span></a></li></ol></li><li class="nav-item nav-level-3"><a class="nav-link" href="#编译并安装-Nginx"><span class="nav-number">3.</span> <span class="nav-text">编译并安装 Nginx</span></a><ol class="nav-child"><li class="nav-item nav-level-4"><a class="nav-link" href="#Nginx-1-15-5"><span class="nav-number">3.1.</span> <span class="nav-text">Nginx 1.15.5</span></a></li></ol></li><li class="nav-item nav-level-3"><a class="nav-link" href="#管理脚本与自启动"><span class="nav-number">4.</span> <span class="nav-text">管理脚本与自启动</span></a></li><li class="nav-item nav-level-3"><a class="nav-link" href="#Nginx-全局配置"><span class="nav-number">5.</span> <span class="nav-text">Nginx 全局配置</span></a></li><li class="nav-item nav-level-3"><a class="nav-link" href="#WEB-站点配置"><span class="nav-number">6.</span> <span class="nav-text">WEB 站点配置</span></a></li><li class="nav-item nav-level-3"><a class="nav-link" href="#日志自动切分"><span class="nav-number">7.</span> <span class="nav-text">日志自动切分</span></a></li><li class="nav-item nav-level-3"><a class="nav-link" href="#安全测试和评分"><span class="nav-number">8.</span> <span class="nav-text">安全测试和评分</span></a></li><li class="nav-item nav-level-3"><a class="nav-link" href="#Docker"><span class="nav-number">9.</span> <span class="nav-text">Docker</span></a><ol class="nav-child"><li class="nav-item nav-level-4"><a class="nav-link" href="#Nginx的Dockerfile"><span class="nav-number">9.1.</span> <span class="nav-text">Nginx的Dockerfile</span></a></li></ol></li></ol></div>
            

          </div>
        </section>
      <!--/noindex-->
      

      

    </div>
  </aside>


        
      </div>
    </main>

    <footer id="footer" class="footer">
      <div class="footer-inner">
        <div class="copyright">&copy; <span itemprop="copyrightYear">2018</span>
  
  <span class="with-love" id="heart">
    <i class="fa fa-heart"></i>
  </span>
  <span class="author" itemprop="copyrightHolder">yszar</span>

  

  
</div>


  










<div class="theme-info">
  <div class="powered-by"></div>
  <span class="post-count">博客全站共38.6k字</span>
</div>
<div class="post-count">
	<a href="http://www.miitbeian.gov.cn/" rel="external nofollow noopener noreferrer" target="_blank">陇ICP备15003024号</a>
</div>


<div class="weixin-box">
  <div class="weixin-menu">
    <div class="weixin-hover">
      <div class="weixin-description">微信扫一扫，订阅本博客</div>
    </div>
  </div>
</div>
        








        
      </div>
    </footer>

    
      <div class="back-to-top">
        <i class="fa fa-arrow-up"></i>
        
          <span id="scrollpercent"><span>0</span>%</span>
        
      </div>
    

    
	
    

    
  </div>

  

<script type="text/javascript">
  if (Object.prototype.toString.call(window.Promise) !== '[object Function]') {
    window.Promise = null;
  }
</script>












  















  
  
    <script type="text/javascript" src="//cdn.jsdelivr.net/npm/jquery@2.1.3/dist/jquery.min.js"></script>
  

  
  
    <script type="text/javascript" src="//cdn.jsdelivr.net/velocity/1.2.3/velocity.min.js"></script>
  

  
  
    <script type="text/javascript" src="//cdn.jsdelivr.net/velocity/1.2.3/velocity.ui.min.js"></script>
  

  
  
    <script type="text/javascript" src="//cdn.jsdelivr.net/fancybox/2.1.5/jquery.fancybox.pack.js"></script>
  


  


  <script type="text/javascript" src="/js/src/utils.js?v=6.4.2"></script>

  <script type="text/javascript" src="/js/src/motion.js?v=6.4.2"></script>



  
  

  
  <script type="text/javascript" src="/js/src/scrollspy.js?v=6.4.2"></script>
<script type="text/javascript" src="/js/src/post-details.js?v=6.4.2"></script>



  


  <script type="text/javascript" src="/js/src/bootstrap.js?v=6.4.2"></script>



  



  










   
     
       <script src="https://unpkg.com/gitalk/dist/gitalk.min.js"></script>

      <script src="/js/src/md5.min.js"></script>

       <script type="text/javascript">
         const gitalk = new Gitalk({
           clientID: '54f26977793794b45255',
           clientSecret: '568cccb3bdde42eca6c05ab0680b4617bbb58c4f',
           repo: 'yszar.github.io',
           owner: 'yszar',
           admin: 'yszar'.split(','),
           id: md5(location.pathname),
           pagerDirection: 'first',
           // facebook-like distraction free mode
           distractionFreeMode: false
         })
         gitalk.render('gitalk-container')
       </script>
     
   
 
  

  <script type="text/javascript">
    // Popup Window;
    var isfetched = false;
    var isXml = true;
    // Search DB path;
    var search_path = "search.xml";
    if (search_path.length === 0) {
      search_path = "search.xml";
    } else if (/json$/i.test(search_path)) {
      isXml = false;
    }
    var path = "/" + search_path;
    // monitor main search box;

    var onPopupClose = function (e) {
      $('.popup').hide();
      $('#local-search-input').val('');
      $('.search-result-list').remove();
      $('#no-result').remove();
      $(".local-search-pop-overlay").remove();
      $('body').css('overflow', '');
    }

    function proceedsearch() {
      $("body")
        .append('<div class="search-popup-overlay local-search-pop-overlay"></div>')
        .css('overflow', 'hidden');
      $('.search-popup-overlay').click(onPopupClose);
      $('.popup').toggle();
      var $localSearchInput = $('#local-search-input');
      $localSearchInput.attr("autocapitalize", "none");
      $localSearchInput.attr("autocorrect", "off");
      $localSearchInput.focus();
    }

    // search function;
    var searchFunc = function(path, search_id, content_id) {
      'use strict';

      // start loading animation
      $("body")
        .append('<div class="search-popup-overlay local-search-pop-overlay">' +
          '<div id="search-loading-icon">' +
          '<i class="fa fa-spinner fa-pulse fa-5x fa-fw"></i>' +
          '</div>' +
          '</div>')
        .css('overflow', 'hidden');
      $("#search-loading-icon").css('margin', '20% auto 0 auto').css('text-align', 'center');

      

      $.ajax({
        url: path,
        dataType: isXml ? "xml" : "json",
        async: true,
        success: function(res) {
          // get the contents from search data
          isfetched = true;
          $('.popup').detach().appendTo('.header-inner');
          var datas = isXml ? $("entry", res).map(function() {
            return {
              title: $("title", this).text(),
              content: $("content",this).text(),
              url: $("url" , this).text()
            };
          }).get() : res;
          var input = document.getElementById(search_id);
          var resultContent = document.getElementById(content_id);
          var inputEventFunction = function() {
            var searchText = input.value.trim().toLowerCase();
            var keywords = searchText.split(/[\s\-]+/);
            if (keywords.length > 1) {
              keywords.push(searchText);
            }
            var resultItems = [];
            if (searchText.length > 0) {
              // perform local searching
              datas.forEach(function(data) {
                var isMatch = false;
                var hitCount = 0;
                var searchTextCount = 0;
                var title = data.title.trim();
                var titleInLowerCase = title.toLowerCase();
                var content = data.content.trim().replace(/<[^>]+>/g,"");
                
                var contentInLowerCase = content.toLowerCase();
                var articleUrl = decodeURIComponent(data.url);
                var indexOfTitle = [];
                var indexOfContent = [];
                // only match articles with not empty titles
                if(title != '') {
                  keywords.forEach(function(keyword) {
                    function getIndexByWord(word, text, caseSensitive) {
                      var wordLen = word.length;
                      if (wordLen === 0) {
                        return [];
                      }
                      var startPosition = 0, position = [], index = [];
                      if (!caseSensitive) {
                        text = text.toLowerCase();
                        word = word.toLowerCase();
                      }
                      while ((position = text.indexOf(word, startPosition)) > -1) {
                        index.push({position: position, word: word});
                        startPosition = position + wordLen;
                      }
                      return index;
                    }

                    indexOfTitle = indexOfTitle.concat(getIndexByWord(keyword, titleInLowerCase, false));
                    indexOfContent = indexOfContent.concat(getIndexByWord(keyword, contentInLowerCase, false));
                  });
                  if (indexOfTitle.length > 0 || indexOfContent.length > 0) {
                    isMatch = true;
                    hitCount = indexOfTitle.length + indexOfContent.length;
                  }
                }

                // show search results

                if (isMatch) {
                  // sort index by position of keyword

                  [indexOfTitle, indexOfContent].forEach(function (index) {
                    index.sort(function (itemLeft, itemRight) {
                      if (itemRight.position !== itemLeft.position) {
                        return itemRight.position - itemLeft.position;
                      } else {
                        return itemLeft.word.length - itemRight.word.length;
                      }
                    });
                  });

                  // merge hits into slices

                  function mergeIntoSlice(text, start, end, index) {
                    var item = index[index.length - 1];
                    var position = item.position;
                    var word = item.word;
                    var hits = [];
                    var searchTextCountInSlice = 0;
                    while (position + word.length <= end && index.length != 0) {
                      if (word === searchText) {
                        searchTextCountInSlice++;
                      }
                      hits.push({position: position, length: word.length});
                      var wordEnd = position + word.length;

                      // move to next position of hit

                      index.pop();
                      while (index.length != 0) {
                        item = index[index.length - 1];
                        position = item.position;
                        word = item.word;
                        if (wordEnd > position) {
                          index.pop();
                        } else {
                          break;
                        }
                      }
                    }
                    searchTextCount += searchTextCountInSlice;
                    return {
                      hits: hits,
                      start: start,
                      end: end,
                      searchTextCount: searchTextCountInSlice
                    };
                  }

                  var slicesOfTitle = [];
                  if (indexOfTitle.length != 0) {
                    slicesOfTitle.push(mergeIntoSlice(title, 0, title.length, indexOfTitle));
                  }

                  var slicesOfContent = [];
                  while (indexOfContent.length != 0) {
                    var item = indexOfContent[indexOfContent.length - 1];
                    var position = item.position;
                    var word = item.word;
                    // cut out 100 characters
                    var start = position - 20;
                    var end = position + 80;
                    if(start < 0){
                      start = 0;
                    }
                    if (end < position + word.length) {
                      end = position + word.length;
                    }
                    if(end > content.length){
                      end = content.length;
                    }
                    slicesOfContent.push(mergeIntoSlice(content, start, end, indexOfContent));
                  }

                  // sort slices in content by search text's count and hits' count

                  slicesOfContent.sort(function (sliceLeft, sliceRight) {
                    if (sliceLeft.searchTextCount !== sliceRight.searchTextCount) {
                      return sliceRight.searchTextCount - sliceLeft.searchTextCount;
                    } else if (sliceLeft.hits.length !== sliceRight.hits.length) {
                      return sliceRight.hits.length - sliceLeft.hits.length;
                    } else {
                      return sliceLeft.start - sliceRight.start;
                    }
                  });

                  // select top N slices in content

                  var upperBound = parseInt('1');
                  if (upperBound >= 0) {
                    slicesOfContent = slicesOfContent.slice(0, upperBound);
                  }

                  // highlight title and content

                  function highlightKeyword(text, slice) {
                    var result = '';
                    var prevEnd = slice.start;
                    slice.hits.forEach(function (hit) {
                      result += text.substring(prevEnd, hit.position);
                      var end = hit.position + hit.length;
                      result += '<b class="search-keyword">' + text.substring(hit.position, end) + '</b>';
                      prevEnd = end;
                    });
                    result += text.substring(prevEnd, slice.end);
                    return result;
                  }

                  var resultItem = '';

                  if (slicesOfTitle.length != 0) {
                    resultItem += "<li><a href='" + articleUrl + "' class='search-result-title'>" + highlightKeyword(title, slicesOfTitle[0]) + "</a>";
                  } else {
                    resultItem += "<li><a href='" + articleUrl + "' class='search-result-title'>" + title + "</a>";
                  }

                  slicesOfContent.forEach(function (slice) {
                    resultItem += "<a href='" + articleUrl + "'>" +
                      "<p class=\"search-result\">" + highlightKeyword(content, slice) +
                      "...</p>" + "</a>";
                  });

                  resultItem += "</li>";
                  resultItems.push({
                    item: resultItem,
                    searchTextCount: searchTextCount,
                    hitCount: hitCount,
                    id: resultItems.length
                  });
                }
              })
            };
            if (keywords.length === 1 && keywords[0] === "") {
              resultContent.innerHTML = '<div id="no-result"><i class="fa fa-search fa-5x" /></div>'
            } else if (resultItems.length === 0) {
              resultContent.innerHTML = '<div id="no-result"><i class="fa fa-frown-o fa-5x" /></div>'
            } else {
              resultItems.sort(function (resultLeft, resultRight) {
                if (resultLeft.searchTextCount !== resultRight.searchTextCount) {
                  return resultRight.searchTextCount - resultLeft.searchTextCount;
                } else if (resultLeft.hitCount !== resultRight.hitCount) {
                  return resultRight.hitCount - resultLeft.hitCount;
                } else {
                  return resultRight.id - resultLeft.id;
                }
              });
              var searchResultList = '<ul class=\"search-result-list\">';
              resultItems.forEach(function (result) {
                searchResultList += result.item;
              })
              searchResultList += "</ul>";
              resultContent.innerHTML = searchResultList;
            }
          }

          if ('auto' === 'auto') {
            input.addEventListener('input', inputEventFunction);
          } else {
            $('.search-icon').click(inputEventFunction);
            input.addEventListener('keypress', function (event) {
              if (event.keyCode === 13) {
                inputEventFunction();
              }
            });
          }

          // remove loading animation
          $(".local-search-pop-overlay").remove();
          $('body').css('overflow', '');

          proceedsearch();
        }
      });
    }

    // handle and trigger popup window;
    $('.popup-trigger').click(function(e) {
      e.stopPropagation();
      if (isfetched === false) {
        searchFunc(path, 'local-search-input', 'local-search-result');
      } else {
        proceedsearch();
      };
    });

    $('.popup-btn-close').click(onPopupClose);
    $('.popup').click(function(e){
      e.stopPropagation();
    });
    $(document).on('keyup', function (event) {
      var shouldDismissSearchPopup = event.which === 27 &&
        $('.search-popup').is(':visible');
      if (shouldDismissSearchPopup) {
        onPopupClose();
      }
    });
  </script>





  

  
  <script>
    
    function addCount(Counter) {
      var $visitors = $(".leancloud_visitors");
      var url = $visitors.attr('id').trim();
      var title = $visitors.attr('data-flag-title').trim();

      Counter('get', '/classes/Counter', { where: JSON.stringify({ url }) })
        .done(function ({ results }) {
          if (results.length > 0) {
            var counter = results[0];
            
              var $element = $(document.getElementById(url));
              $element.find('.leancloud-visitors-count').text(counter.time + 1);
            
            Counter('put', `/classes/Counter/${counter.objectId}`, JSON.stringify({ time: { "__op":"Increment", "amount":1 } }))
            
            .fail(function ({ responseJSON }) {
                console.log('Failed to save Visitor num, with error message: ' + responseJSON.error);
            })
          } else {
            
              Counter('post', '/classes/Counter', JSON.stringify({ title: title, url: url, time: 1}))
                .done(function () {
                  var $element = $(document.getElementById(url));
                  $element.find('.leancloud-visitors-count').text(1);
                })
                .fail(function () {
                  console.log('Failed to create');
                });
            
          }
        })
      .fail(function ({ responseJSON }) {
        console.log('LeanCloud Counter Error:' + responseJSON.code + " " + responseJSON.error);
      });
    }
    

    $(function() {
      $.get('https://app-router.leancloud.cn/2/route?appId=' + "iUS887d8BnkY3Gqc9FJX70fE-gzGzoHsz")
        .done(function ({ api_server }) {
          var Counter = function (method, url, data) {
            return $.ajax({
              method: method,
              url: `https://${api_server}/1.1${url}`,
              headers: {
                'X-LC-Id': "iUS887d8BnkY3Gqc9FJX70fE-gzGzoHsz",
                'X-LC-Key': "ekF4kKyQDgrDkIBadj3IDrVA",
                'Content-Type': 'application/json',
              },
              data: data,
            });
          };
          
          addCount(Counter);
          
        })
    });
  </script>



  

  

  

  
  
  <script type="text/javascript">
  wpac_init = window.wpac_init || [];
  wpac_init.push({widget: 'Rating', id: 14244,
    el: 'wpac-rating',
    color: 'fc6423'
  });
  (function() {
    if ('WIDGETPACK_LOADED' in window) return;
    WIDGETPACK_LOADED = true;
    var mc = document.createElement('script');
    mc.type = 'text/javascript';
    mc.async = true;
    mc.src = '//embed.widgetpack.com/widget.js';
    var s = document.getElementsByTagName('script')[0]; s.parentNode.insertBefore(mc, s.nextSibling);
  })();
  </script>


  

  

  

  

  
  <style>
    .copy-btn {
      display: inline-block;
      padding: 6px 12px;
      font-size: 13px;
      font-weight: 700;
      line-height: 20px;
      color: #333;
      white-space: nowrap;
      vertical-align: middle;
      cursor: pointer;
      background-color: #eee;
      background-image: linear-gradient(#fcfcfc, #eee);
      border: 1px solid #d5d5d5;
      border-radius: 3px;
      user-select: none;
      outline: 0;
    }

    .highlight-wrap .copy-btn {
      transition: opacity .3s ease-in-out;
      opacity: 0;
      padding: 2px 6px;
      position: absolute;
      right: 4px;
      top: 8px;
    }

    .highlight-wrap:hover .copy-btn,
    .highlight-wrap .copy-btn:focus {
      opacity: 1
    }

    .highlight-wrap {
      position: relative;
    }
  </style>
  <script>
    $('.highlight').each(function (i, e) {
      var $wrap = $('<div>').addClass('highlight-wrap')
      $(e).after($wrap)
      $wrap.append($('<button>').addClass('copy-btn').append('复制').on('click', function (e) {
        var code = $(this).parent().find('.code').find('.line').map(function (i, e) {
          return $(e).text()
        }).toArray().join('\n')
        var ta = document.createElement('textarea')
        document.body.appendChild(ta)
        ta.style.position = 'absolute'
        ta.style.top = '0px'
        ta.style.left = '0px'
        ta.value = code
        ta.select()
        ta.focus()
        var result = document.execCommand('copy')
        document.body.removeChild(ta)
        
          if(result)$(this).text('复制成功')
          else $(this).text('复制失败')
        
        $(this).blur()
      })).on('mouseleave', function (e) {
        var $b = $(this).find('.copy-btn')
        setTimeout(function () {
          $b.text('复制')
        }, 300)
      }).append(e)
    })
  </script>


  
</body>
</html>
